<template>
	<view  class="message-section" :class="config.style">

		<view class="message-list-section" ref="messageSection">
			<scroll-view class="msgs" :style="{height: msgsHeight + 'px'}" scroll-y="true" :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop"
			 :scroll-into-view="scrollToView" upper-threshold="50">
				<view class="msgs-list">
					<view class="row" v-for="(item,index) in msgs" :key="index" :id="item.ID">
						<!-- 用户消息 -->
						<template>
							<!-- 自己发出的消息 -->
							<view class="my" v-if="item.self">
								<!-- 左-消息 -->
								<view class="left">
									<!-- 文字消息 -->
									<view class="bubble" :class="item.type">
										<rich-text :nodes="nodesFliter(item.content)"></rich-text>
									</view>
								</view>
								<!-- 右-头像 -->
								<view class="right">
									<image :src="item.avatar"></image>
								</view>
							</view>
							<!-- 别人发出的消息 -->
							<view class="other" v-else>
								<!-- 左-头像 -->
								<view class="left">
									<image :src="item.avatar"></image>
								</view>
								<!-- 右-用户名称-时间-消息 -->
								<view class="right">
									<view class="username">
										<view class="name">{{item.send}}</view>
										<view class="time">{{item.time}}</view>
									</view>
								
									<!-- 文字消息 -->
									<view class="bubble" :class="item.type">
										<rich-text :nodes="nodesFliter(item.content)"></rich-text>
									</view>
								</view>
							</view>
						</template>
					</view>
				</view>
			</scroll-view>
		</view>
		
		<view class="message-send-section">
			<view class="message">
				<view class="uni-form-item uni-column">
					<input class="uni-input" name="content" placeholder="互动内容发布" confirm-type="send" @confirm="msgSubmit"/>
				</view>
			</view>
			<view class="emoji" @click="emojiShow()">
				<view class="icon">
					<image mode="widthFix" src="../../../static/images/emoji.png" @error="imageError" class="image"></image>
				</view>
			</view>
		</view>
		
		<uni-popup ref="emojiPopup" type="bottom">
			<view class="emoji-list" >
				<view class="item" v-for="(item,index) in emoji" :key="index">
					<image mode="widthFix" :src="item.url" @click="emojiSend(index)"></image>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>

	//import MUUTIM from 'tim-js-sdk'
	export default {
		
		props: {
			config: {
				type: Object,
				default: {},
			},
			userInfo: {
				type: Object,
				default: {},
			},
			roomData: {
				type: Object,
				default: {},
			}
		},
		data() {
			return {
				sdkAppId: '',
				userSig: '',
				enableSpeaking : true, // 聊天禁用状态, 默认允许发言
				
				//消息列表
				msgs: [],
				msgsHeight: 0,
				imSendMsg: {},
				isHistoryLoading:false,
				scrollAnimation:false,
				scrollTop:0,
				scrollToView:'',
				emoji: [
					
				],
				
				nodes: [{
					name: 'div',
					attrs: {
						class: 'div-class',
						style: 'line-height: 60px; color: red; text-align:center;'
					},
					children: [{
						type: 'text',
						text: 'Hello&nbsp;uni-app!'
					}]
				}],
				tim: {},
			}
		},
		onLoad(option) { //option为object类型，会序列化上个页面传递的参数
		    console.log(option); //打印出上个页面传递的参数。
		},
		onReady() {
			let that=this;
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					console.log(res)
					let selector = uni.createSelectorQuery().in(that).select('.message-section')
					selector.boundingClientRect(data=>{
						console.log(data)
						let msgsHeight = data.height - 51
						that.msgsHeight = msgsHeight
					}).exec()
					
				}
			})
		},
		created() {
			console.log(this.userInfo)
			this.getSign()
			this.getEmojiList()
		},
		methods: {
			scrollToBottom: function(){
				let _this = this;
				let selector = uni.createSelectorQuery().in(this).select('.msgs-list')
				selector.boundingClientRect(data=>{
					console.log(data)
					let msgsHeight = data.height
					this.scrollTop = msgsHeight
				}).exec()
			},
			//签名授权登录
			getSign: function() {
				let _this = this;
				//获取用户验签数据
				//获取全局配置
				this.util.request({
					url : 'entry/wxapp/livecourse',
					data: {
						'action': 'usersig',
						'm' : 'muu_classroom'
					},
					success: function (res) {
						//console.log(res.data);
						if (res.data.code == 200) {
							_this.userSig = res.data.data.userSig;
							_this.sdkAppId = res.data.data.sdkappid;
							_this.initTim()
						}
					}
				})
			},
			
			/**
			 * 初始化即时通讯TIM
			 */
			initTim: function(){
				let _this = this;

				//创建即时通讯IM实例
				this.tim = MUUTIM.create({SDKAppID: this.sdkAppId}); // SDK 实例通常用 tim 表示
				//接收消息监听事件
				let onMessageReceived = function(event) {
					// 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
					// event.name - TIM.EVENT.MESSAGE_RECEIVED
					// event.data - 存储 Message 对象的数组 - [Message]
					console.log('接收消息监听')
					console.log(event);
					let type = event.data[0].type;
					if(type == 'TIMTextElem'){
						//收到文本消息
						_this.showMessageInBox(event.data[0].nick, event.data[0].payload.text,event.data[0].avatar);
					}
					if(type == 'TIMGroupTipElem'){
						//收到群组消息
						//_this.showMessageInBox(event.data[0].nick, '进入课堂',event.data[0].avatar);
					}
					if(type == "TIMFaceElem"){
						//收到表情消息
						var emoji = '<img src="' +event.data[0].payload.data+ '" />';
						_this.showMessageInBox(event.data[0].nick, emoji, event.data[0].avatar, false, 'img');
					}
					if(type == "TIMCustomElem"){
						//自定义消息
						if(event.data[0].payload.description == 'nospeaking'){
							if(event.data[0].payload.data == '1'){
								//禁言
								_this.enableSpeaking = false;
							}else{
								//开放发言
								_this.enableSpeaking = true;
							}
						}
					}
				};
				
				this.tim.on(MUUTIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
				//监听SDKREADY状态
				let onSdkReady = function(event) {
					//创建并加入群组
					_this.joinGroup(); //进入群组
				};
				this.tim.on(MUUTIM.EVENT.SDK_READY, onSdkReady);
				console.log(this.userInfo)
				//登录即时通讯
				this.tim.login({
					userID: _this.userInfo.memberInfo.uid, 
					userSig: _this.userSig
				}).then(function(imResponse) {
					console.log(imResponse.data); // 登录成功
					//_this.showMessageInBox('课堂助手', 'IM登录成功');
					if (imResponse.data.repeatLogin === true) {
						// 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
						console.log(imResponse.data.errorInfo);
					}
				}).catch(function(imError) {
					console.warn('login error:', imError); // 登录失败的相关信息
				});
			},
			
			//加入群组
			joinGroup: function() {
				let _this = this;
				//强制转化为字符串类型
				let promise = _this.tim.joinGroup({
					groupID: _this.roomData.id,
					type: MUUTIM.TYPES.GRP_AVCHATROOM 
				});
				promise.then(function(imResponse) {
					switch (imResponse.data.status) {
						case MUUTIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: // 等待管理员同意
						break;
						case MUUTIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
							console.log('加入群组成功')
							console.log(imResponse.data.group); // 加入的群组资料
							//_this.showMessageInBox('课堂助手', "加入群组成功");
							//更新个人资料
							console.log(_this.userInfo.memberInfo.avatar)
							let promise = _this.tim.updateMyProfile({
								nick: _this.userInfo.memberInfo.nickname,
								avatar: _this.userInfo.memberInfo.avatar,
								gender: MUUTIM.TYPES.GENDER_MALE,
								allowType: MUUTIM.TYPES.ALLOW_TYPE_ALLOW_ANY
							});
							promise.then(function(imResponse) {
								//console.log(imResponse.data); // 更新资料成功
								//发生一条群消息
								_this.sendOnlineMsg();
								_this.showMessageInBox('课堂助手', _this.userInfo.memberInfo.nickname + '进入了课堂');
							}).catch(function(imError) {
								console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
							});
						break;
						case MUUTIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
						break;
					}
				}).catch(function(imError){
					console.warn('joinGroup error:', imError); // 申请加群失败的相关信息
				});
			},
			
			/**
			 * 文本消息提交
			 */
			msgSubmit: function(e){
				console.log(e)
				let text = e.detail.value
				this.imSendMsg.data = text
				this.sendMsg()
			},
			
			/**
			 * 发送上线消息
			 * @return {[type]} [description]
			 */
			sendOnlineMsg: function() {
				let _this = this;
				// 创建消息实例，接口返回的实例可以上屏
				let message = this.tim.createTextMessage({
					to: _this.roomData.id,
					conversationType: MUUTIM.TYPES.CONV_GROUP,
					payload: {
						text: _this.userInfo.memberInfo.nickname + ' 进入了课堂',
					}
				});
				//发送消息
				let promise = _this.tim.sendMessage(message);
				promise.then(function(imResponse) {
					// 发送成功
					console.log('发送上线消息');
					console.log(imResponse.data);
				}).catch(function(imError) {
					// 发送失败
					console.warn('sendMessage error:', imError);
				});
			},
			
			/**
			 * 发送普通文本消息
			 */
			sendMsg: function() {
				if (!this.imSendMsg.data) {
					this.showErrorTip(`不能发送空消息`);
					return;
				}
				let _this = this;
				let text = this.imSendMsg.data;
				let to = this.imSendMsg.toUser;
		
			  // 发送文本消息
			  let sendMessage = function(to, text, type = MUUTIM.TYPES.CONV_GROUP){
				// 创建消息实例，接口返回的实例可以上屏
				let message = _this.tim.createTextMessage({
				  to: to,
				  conversationType: type,
				  payload: {
					text: text
				  }
				});
				//发送消息
				let promise = _this.tim.sendMessage(message);
					promise.then(function(imResponse) {
					  // 发送成功
					  console.log(imResponse.data);
					  //显示自己发布的消息
					  _this.showMessageInBox(_this.userInfo.memberInfo.nickname, text, _this.userInfo.memberInfo.avatar,true);
					}).catch(function(imError) {
					  // 发送失败
					  console.warn('sendMessage error:', imError);
					});
			  };
			  // C2C 文本
			  if (this.imSendMsg.toUser) {
				sendMessage(this.imSendMsg.toUser, this.imSendMsg.data ,MUUTIM.TYPES.CONV_C2C);
			  }else{
				//发群组
				sendMessage(_this.roomData.id, this.imSendMsg.data, MUUTIM.TYPES.CONV_GROUP);
			  }
			  //清空文本框
			  this.imSendMsg.data = '';
			  this.imSendMsg.toUser = '';
			},
		
			/**
			 * 发送自定义消息
			 * 如：发礼物、发系统消息、发打赏等等
			 */
			sendCustomGroupMsg: function() {
		
			  let _this = this;
			  let to = this.imSendMsg.toUser;
			  let payload = {
				data: '',// 用于标识该消息的类型消息
				description: ''// 标识该消息的值或描述
			  };
			  
			  let sendMessage = function(to, payload = {}, type = TIM.TYPES.CONV_GROUP){
				// 创建消息实例，接口返回的实例可以上屏
				let message = tim.createCustomMessage({
				  to: to,
				  conversationType: type,
				  payload: payload,
				});
				// 发送消息
				let promise = tim.sendMessage(message);
				promise.then(function(imResponse) {
				  // 发送成功
				  console.log(imResponse);
				  
				}).catch(function(imError) {
				  // 发送失败
				  console.warn('sendMessage error:', imError);
				});
			  }
			  // C2C
			  if (this.imSendMsg.toUser) {
				sendMessage(this.imSendMsg.toUser, this.imSendMsg.data ,MUUTIM.TYPES.CONV_C2C);
			  }else{
				//发群组
				sendMessage(this.roomData.id, this.imSendMsg.data, MUUTIM.TYPES.CONV_GROUP);
			  }
			},
		
			/**
			 * 发送表情消息(仅支持群组)
			 */
			sendFaceGroupMsg: function(index, data, userID) {
			  let _this = this;
			  
			  let type;
			  let to;
			  if(userID){
				type = MUUTIM.TYPES.CONV_C2C;
				to = userID;
			  }else{
				type = MUUTIM.TYPES.CONV_GROUP;
				to = _this.roomData.id; //群组ID即直播间ID
			  }
			  data = data || 'default'; //默认额外数据为default
			  //发现发生整数型无效，转为字符型
			  let message = this.tim.createFaceMessage({
				to: to,
				conversationType: type,
				// 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
				// 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
				// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
				payload: {
					index: parseInt(index), // Number 表情索引，用户自定义
					data: data // String 额外数据
				}
			  });
			  // 3. 发送消息
			  let promise = this.tim.sendMessage(message);
			  promise.then(function(imResponse) {
				// 发送成功
				console.log(imResponse);
				//显示自己发布的消息
				var emoji = '<img src="' +imResponse.data.message.payload.data+ '" />';
				_this.showMessageInBox(_this.userInfo.memberInfo.nickname, emoji, _this.userInfo.memberInfo.avatar,true,'img');
				//隐藏表情popup框
				_this.$refs.emojiPopup.close()
			  }).catch(function(imError) {
				// 发送失败
				console.warn('sendMessage error:', imError);
			  });
			},
			
			/**
			 * 发送表情消息
			 */
			emojiSend: function(index){
				let thisEmoji = this.emoji[index]
				console.log(thisEmoji)
				let send_index = parseInt(thisEmoji.index)
				var url = thisEmoji.url
				//console.log(index);
				//console.log(url);
				this.sendFaceGroupMsg(send_index,url)
			},
			
			/**
			 * 显示表情列表
			 */
			emojiShow: function(){
				console.log('show emoji')
				this.$refs.emojiPopup.open()
			},
			
			/**
			 * 获取表情列表
			 */
			getEmojiList: function(){
				let _this = this;
				//获取用户验签数据
				//获取全局配置
				this.util.request({
					url : 'entry/wxapp/livecourse',
					data: {
						'action': 'emoji',
						'm' : 'muu_classroom'
					},
					success: function (res) {
						//console.log(res.data);
						if (res.data.code == 200) {
							console.log(res.data.data);
							_this.emoji = res.data.data;
						}
					}
				})
			},
			
			/**
			* 互动区聊天消息
			* @param  {[type]} fromUserId [description]
			* @param  {[type]} text       [description]
			* @param  {[type]} avatar     [description]
			* @param  {[type]} self       [自己发布的信息，在右侧显示]
			* @param  {[type]}            [description]
			*/
			showMessageInBox: function(fromUser, text, avatar, self, type) {
				var d = new Date();
				var time = `${('0' + d.getHours()).substr(-2)}:${('0' + d.getMinutes()).substr(-2)}:${('0' + d.getSeconds()).substr(-2)}.${('00' + d.getMilliseconds()).substr(-3)}`
				avatar = avatar || '../../../static/images/sys.png'
				self = self || false;
				type = type || 'text';
				this.msgs.push({
					time: time,
					send: fromUser,
					content: text,
					avatar: avatar,
					self: self,
					type: type,
				});
				console.log(this.msgs)
				this.scrollToBottom()
			},
		
			/**
			 * 退出课堂
			 */
			quitClassroom: function() {
				let _this = this;
				let promise = this.tim.logout();
					promise.then(function(imResponse) {
						console.log(imResponse.data); // 登出成功
						//_this.status = _this.STATUS_LOGINED;
						_this.showMessageInBox('课堂助手', "退出课堂成功");
						//_this.clearClassInfo();
					}).catch(function(imError) {
						console.warn('logout error:', imError);
					});
			},
			
			//聊天的节点加上外层的div
			nodesFliter(str){
				str = str.replace('<img ','<img style="width:60px;height:60px;" ')
				let nodeStr = '<div style="align-items: center;word-wrap:break-word;">'+str+'</div>' 
				return nodeStr
			},
			//时间过滤
			timeFliter(timer){
				let timeData = new Date(timer*1000)
				let str = this.$commen.dateTimeFliter(timeData)		 
				return str
			},
		},
		onBackPress(){
			this.quitClassroom()
		}
	}
</script>

<style lang="scss">
	.message-section {
		height: 100%;
	}
	
	.message-list-section {
		
		.row {
			padding: 8px;
			.system{
				display: flex;
				justify-content: center;
				view{
					padding: 0 30upx;
					height: 50upx;
					display: flex;
					justify-content: center;
					align-items: center;
					background-color: #c9c9c9;
					color: #fff;
					font-size: 24upx;
					border-radius: 40upx;
				}
				.red-envelope{
					image{
						margin-right: 5upx;
						width: 30upx;
						height: 30upx;
					}
				}
			}

			.my .left,.other .right{
				width: 100%;
				display: flex;
				.bubble{
					max-width: 70%;
					min-height: 50rpx;
					border-radius: 10rpx;
					padding: 10rpx;
					display: flex;
					align-items: center;
					font-size: 28rpx;
					word-break: break-word;
					&.img{
						background-color: transparent;
						padding:0;
						overflow: hidden;
						image{
							max-width: 350rpx;
							max-height: 350rpx;
						}
					}
					&.red-envelope{
						background-color: transparent;
						padding:0;
						overflow: hidden;
						position: relative;
						justify-content: center;
						align-items: flex-start;
						image{
							width: 250upx;
							height: 313upx;
						}
						.tis{
							position: absolute;
							top: 6%;
							font-size: 26upx;
							color: #9c1712;
						}
						.blessing{
							position: absolute;
							bottom: 14%;
							color: #e9b874;
							width: 80%;
							text-align: center;
							overflow: hidden;
							// 最多两行
							display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 2;
						}
					}
					&.voice{
						.icon{
							font-size: 40upx;
							display: flex;
							align-items: center;
						}
						.icon:after
						{
							content:" ";
							width: 53upx;
							height: 53upx;
							border-radius: 100%;
							position: absolute;
							box-sizing: border-box;
						}
						.length{
							font-size: 28upx;
						}
					}
				}
			}
			.my .right,.other .left{
				flex-shrink: 0;
				width: 80upx;
				height: 80upx;
				image{
					width: 80upx;
					height: 80upx;
					border-radius: 10upx;
				}
			}
			.my{
				width: 100%;
				display: flex;
				justify-content: flex-end;
				.left{
					min-height: 80upx;
					
					align-items: center;
					justify-content: flex-end;
					.bubble.text{
						background-color: #f06c7a;
						color: #fff;
						&.voice{
							.icon{
								color: #fff;
							}
							.length{
								margin-right: 20upx;
							}
						}
						&.play{
							@keyframes my-play {
								0% {
									transform: translateX(80%);
								}
								100% {
									transform: translateX(0%);
								}
							}
							.icon:after
							{
								border-left: solid 10upx rgba(240,108,122,.5);
								animation: my-play 1s linear infinite;
							}
						}
					}
					.bubble.img {
						img {
							width: 60px;
							height: 60px;
						}
					}
				}
				.right{
					margin-left: 15upx;
				}
			}
			.other{
				width: 100%;
				display: flex;
				.left{
					margin-right: 15upx;
				}
				.right{
					flex-wrap: wrap;
					.username{
						width: 100%;
						height: 45upx;
						font-size: 24upx;
						color: #999;
						display: flex;
						.name{
							margin-right: 50upx;
						}
					}
					.bubble.text{
						background-color: #fff;
						color: #333;
						&.voice{
							.icon{
								color: #333;
								
							}
							.length{
								margin-left: 20upx;
							}
						}
						&.play{
							@keyframes other-play {
								0% {
									transform: translateX(-80%);
								}
								100% {
									transform: translateX(0%);
								}
							}
							.icon:after
							{
								border-right: solid 10upx rgba(255,255,255,.8);
								
								animation: other-play 1s linear infinite;
							}
						}
					}
					.bubble.img {
						img {
							width: 60px;
							height: 60px;
						}
					}
				}
			}
		}
		
		/*消息列表*/
		.msgs {
			height: 200px;
		}
	}

	.message-send-section {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 51px;
		display: flex;
		border-top: 1px solid #f8f8f8;
		background-color: #fff;
		.message {
			flex: 1;
			padding: 8px;
			.uni-input {
				margin: 0;
				height: 32px;
				background-color: #f2f2f2;
				border-radius: 16px;
				border: 1px solid #eee;
				font-size: 12px;
				padding: 0 10px;
			}
		}
		.emoji {
			width: 40px;
			padding: 8px;
			.icon {
				.image {
					width: 36px;
					height: 36px;
				}
			}
		}
	}
	
	/**表情弹出框**/
	.emoji-list {
		background-color: #fff;
		border-radius: 5px 0 0 5px;
		padding: 5px;
		box-sizing: box;
		.item {
			display: inline-block;
			width: 25%;
			image {
				width: 100%;
				height: auto;
			}
		}
	}
</style>
